<template>
  <div class="container">
    <el-row class="top-search">
      <el-col style="text-align:right;">
        <el-date-picker
          v-model="datePicker1"
          class="w-140"
          size="small"
          type="date"
          align="right"
          value-format="yyyy-MM-dd"
          @change="timeChange"/>
        <el-select v-model="listQuery.platform" class="w-140" size="small">
          <el-option v-for="item in options1" :key="item.value" :label="item.label" :value="item.value"/>
        </el-select>
        <el-select v-model="listQuery.appVersion" class="w-140" size="small">
          <el-option v-for="item in options2" :key="item.value" :label="item.label" :value="item.value"/>
        </el-select>
        <el-select v-model="listQuery.lang" class="w-140" size="small">
          <el-option v-for="item in options3" :key="item.value" :label="item.label" :value="item.value"/>
        </el-select>
        <el-select v-model="listQuery.userSelectType" class="w-140" size="small">
          <el-option v-for="item in options5" :key="item.value" :label="item.label" :value="item.value"/>
        </el-select>
        <el-button type="primary" icon="el-icon-search" size="small" @click="search()">搜索</el-button>
      </el-col>
    </el-row>
    <el-row>
      <el-col>
        <div class="add-time">
          <el-date-picker
            v-model="datePicker2"
            class="w-140"
            size="small"
            type="date"
            align="right"
            value-format="yyyy-MM-dd"/>
          <el-button size="small" @click="addComparisonTime()">添加对比时间</el-button>
          <el-button size="small" icon="el-icon-refresh" @click="refresh"/>
        </div>
      </el-col>
    </el-row>
    <el-row class="echart-list">
      <el-col>
        <div class="echart">
          <div id="read" :style="{width: '100%', height: '380px'}"/>
        </div>
        <el-button @click="show1=!show1">{{ show1 ?'收起数据明细':'展开数据明细' }}</el-button>
        <div v-show="show1">
          <div class="export fr">
            <el-button size="small" round @click="toExport('read')">导出</el-button>
          </div>
          <el-table v-if="tableData1.length > 0 && isUser" :data="tableData1" border>
            <el-table-column prop="duration" label="阅读资讯(条)"/>
            <el-table-column prop="time" label="用户数（人）"/>
            <el-table-column prop="rate" label="用户占比"/>
          </el-table>
          <el-table v-if="tableData1.length > 0 && !isUser" :data="tableData1" border>
            <el-table-column prop="duration" label="阅读资讯(条)"/>
            <el-table-column prop="time" label="会员数（人）"/>
            <el-table-column prop="rate" label="会员占比"/>
          </el-table>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import echarts from 'echarts';
import timeUtils from '@/utils/timeHandle.js';
import { exportJsonToExcel, formatJson } from '@/utils/excel/Export2Excel';
import {
  getAppVersionListApi,
  getUserReadListApi
} from '@/api/user-analysis.js';
// 用户导出
const HeadWithOutWeek = {
  read: [
    {
      prop: 'duration',
      label: '阅读资讯(条)'
    },
    {
      prop: 'time',
      label: '用户数（人）'
    },
    {
      prop: 'rate',
      label: '用户占比'
    }
  ]
};
// 会员导出
const HeadWithOutWeekMember = {
  read: [
    {
      prop: 'duration',
      label: '阅读资讯(条)'
    },
    {
      prop: 'time',
      label: '会员数（人）'
    },
    {
      prop: 'rate',
      label: '会员占比'
    }
  ]
};
export default {
  data() {
    return {
      tableName: {
        read: '阅读资讯数量'
      },
      tableHead: HeadWithOutWeek,
      show1: false,
      activeNames: 1,
      options1: [{
        value: -1,
        label: '全部渠道'
      }, {
        value: 1,
        label: 'Android'
      }, {
        value: 2,
        label: 'IOS'
      }],
      options2: [{
        value: null,
        label: '全部版本'
      }],
      options3: [{
        value: -1,
        label: '全部系统语言'
      }, {
        value: 1,
        label: '中文'
      }, {
        value: 2,
        label: '柬文'
      }, {
        value: 3,
        label: '英文'
      }],
      options4: [{
        value: null,
        label: '所在地区'
      }, {
        value: 'China',
        label: '中国'
      }, {
        value: 'Cambodia',
        label: '柬埔寨'
      }, {
        value: 'Other',
        label: '其他'
      }],
      options5: [{
        value: 1,
        label: '用户'
      }, {
        value: 2,
        label: '会员'
      }],
      datePicker1: timeUtils.timeHandle(new Date().getTime() - 3600 * 1000 * 24 * 1, 'date'),
      datePicker2: null,
      cacheTimes: [], // 缓存选中的多个时间段
      activeName: 'first',
      listQuery: {
        tableSelect: 1, // 1单次使用  2 单日使用
        startTimes: timeUtils.timeHandle(new Date().getTime() - 3600 * 1000 * 24 * 1, 'date'), // 多个时段用逗号隔开
        lang: -1, // 操作语言 1:中文、2:柬文、3:英文
        platform: -1, // 渠道 1:安卓; 2:ios
        appVersion: null, // 版本
        userSelectType: 1, // 用户会员
        dateType: 1 // 0:小时; 1:日期; 2:周;3:月;
      },
      isUser: true,
      tableData1: [],
      exportData: {
        read: null
      },
      echartData1: [],
      xData: [],
      gelend: []
    };
  },
  created() {
    this.getAppVersion();
  },
  mounted() {
    this.search();
  },
  methods: {
    getAppVersion() {
      const that = this;
      getAppVersionListApi().then(res => {
        if (res.code == 200) {
          res.data.forEach(function(item) {
            const obj = {
              value: item,
              label: item
            };
            that.options2.push(obj);
          });
        }
      });
    },

    // 修改时间 清空对比时间
    timeChange(time) {
      this.cacheTimes = [];
      this.datePicker2 = null;
    },

    search() {
      if (!this.datePicker1) {
        this.$message.warning('请输入搜索时间', true);
        return;
      }

      function sortFn(val1, val2) {
        const num1 = Number(val1.replace('-', '').replace('-', ''));
        const num2 = Number(val2.replace('-', '').replace('-', ''));
        return num1 - num2;
      }

      this.listQuery.startTimes = [this.datePicker1, ...this.cacheTimes];
      this.listQuery.startTimes.sort(sortFn);

      this.listQuery.startTimes = this.listQuery.startTimes.join(',');
      this.getData1();
    },

    addComparisonTime() {
      if (this.cacheTimes.length == 5) {
        this.$message.warning('最多只能添加5个对比时间', true);
        return;
      }

      if (!this.datePicker2) {
        this.$message.warning('请先选择对比时间', true);
        return;
      }

      if (this.datePicker2 === this.datePicker1) {
        this.$message.warning('对比时间不应该为当前时间, 请选择其他时间', true);
        return;
      }

      if (this.cacheTimes.indexOf(this.datePicker2) > -1) {
        this.$message.warning('已包含此对比时间，请选择其他时间对比', true);
        return;
      }

      this.cacheTimes.push(this.datePicker2);
      this.search();
    },

    refresh() {
      this.cacheTimes = [];
      this.datePicker2 = null;
      this.search();
    },

    getData1() {
      const myChart = echarts.init(document.getElementById('read'));
      myChart.showLoading();

      this.listQuery.tableSelect = 1;
      getUserReadListApi(this.listQuery).then(res => {
        if (res.code == 200) {
          this.xData = res.data.xAxis;
          const yAxis = res.data.yAxis;
          let currentIndex = 0; // 默认当前时间排第一

          this.gelend = [];
          this.echartData1 = [];
          this.tableData1 = [];

          // 获取echart数据
          for (var i = 0; i < yAxis.length; i++) {
            if (yAxis[i].timeStr == this.datePicker1) {
              currentIndex = i;
            }

            this.gelend.push(yAxis[i].timeStr);
            const obj = {
              name: yAxis[i].timeStr,
              data: yAxis[i].timeData,
              type: 'bar'
            };
            this.echartData1.push(obj);
          }

          // 获取表格数据
          var sum = this.getSum(yAxis[currentIndex].timeData) || 1; // 防止总数为0
          for (let i = 0; i < yAxis[currentIndex].timeData.length; i++) {
            const num = (Math.round(((yAxis[currentIndex].timeData[i]) / sum) * 10000) / 100);
            const rate = num == 0 ? 0 : num + '%';

            const item = {
              duration: this.xData[i],
              time: yAxis[currentIndex].timeData[i],
              rate: rate
            };
            this.tableData1.push(item);
          }

          this.exportData.read = this.tableData1;

          if (this.listQuery.userSelectType == 1) {
            this.isUser = true;
            this.tableHead = HeadWithOutWeek;
          } else {
            this.isUser = false;
            this.tableHead = HeadWithOutWeekMember;
          }

          this.updateEchart1();
        }
      });
    },

    getSum(arr) {
      if (arr.length == 1) {
        return arr[0];
      }
      var sum = arr.reduce(function(prev, curr, idx, arr) {
        return prev + curr;
      });
      return sum;
    },

    updateEchart1() {
      var myChart = echarts.init(document.getElementById('read'));
      myChart.showLoading();

      const option = {
        color: this.$store.state.app.eChartColor,
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            crossStyle: {
              color: '#999'
            }
          }
        },
        toolbox: {
        },
        legend: {
          data: this.legend,
          right: 60,
          top: 10
        },
        grid: {
          left: 60,
          right: 100
        },
        xAxis: [
          {
            name: '(条)',
            type: 'category',
            data: this.xData, // x轴数据
            axisPointer: {
              type: 'shadow'
            }
          }
        ],
        yAxis: {
          name: '(人)'
        },
        series: this.echartData1
      };

      myChart.setOption(option, true);
      myChart.hideLoading();
    },

    toExport(exportName) {
      const exprtTime = timeUtils.timeHandle(new Date().getTime(), 'date');
      const tHeader = this.tableHead[exportName].map(item => item.label);
      const tKey = this.tableHead[exportName].map(item => item.prop);
      const data = formatJson(tKey, this.exportData[exportName]); // 数据格式化
      const fileName = this.tableName[exportName] + exprtTime;
      exportJsonToExcel(tHeader, data, fileName); // 导出文件
    }
  }
};
</script>

<style lang="scss" scoped>
.container {
    padding: 15px;
    .w-140 {
        width: 140px;
    }
    .title {
        height: 32px;
        position: relative;
        p {
            font-size: 22px;
            line-height: 32px;
            text-align: center;
        }
        .btn {
            width: 400px;
            height: 32px;
            position: absolute;
            right: 0;
            top: 0;
        }
    }
    .echart {
        width: 100%;
    }
    .search {
        text-align: right;
        padding: 15px;
        background-color: rgba(240, 242, 245, 1);
    }

    .echart-list {
        padding-top: 30px;
    }
    .add-time {
        width: 360px;
		float: right;
		padding: 35px 10px 0 0;
    }
    .export {
        padding: 10px 0;
    }
}
</style>
